package com.itheima.aspect;

import com.itheima.mapper.EmpLoginLogMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/****
 * 对登录接口进行功能加强：
 *      用户只要登录，不管用户名密码正确与否，都要记录到用户登录表中
 */
@Aspect
@Component
@Slf4j
public class EmpLoginLogAspect {

    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    @Around("execution(* com.itheima.controller.UserLoginController.login(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object proceed = pjp.proceed();
        long end = System.currentTimeMillis();

        EmpLoginLog empLoginLog = new EmpLoginLog();
        Object[] args = pjp.getArgs();
        for (Object arg : args) {
            Emp emp = (Emp) arg;
            empLoginLog.setUsername(emp.getUsername());
            empLoginLog.setPassword(emp.getPassword());
        }

        empLoginLog.setLoginTime(LocalDateTime.now());
        Result result = (Result) proceed;
        empLoginLog.setIsSuccess(result.getCode().shortValue());
        if (result.getCode() == 1) {
            LoginInfo data = (LoginInfo) result.getData();
            empLoginLog.setJwt(data.getToken());
        }

        empLoginLog.setCostTime(end - start);
        log.info("{}.{}方法耗时{}ms", pjp.getTarget().getClass().getName(), pjp.getSignature().getName(), end - start);
        empLoginLogMapper.add(empLoginLog);
        return proceed;
    }
}
